/**
 * Created by MLS on 15/11/13.
 */
(function($){
    var allProjectName = {};
    var projectName = "wms";

    function init(projectName){
        restAjax("index/list",window.RequestMethod.GET,{
            data:{projectName:projectName},
            success:function(res){
                var html = "";
                $(res.data.processInfoList).each(function(index){
                    var processObjList = this.processList;
                    if(processObjList!=null && processObjList.length>0){
                        var role = this.role.name;
                        if(role=='MASTER'){
                            role = "<span data-toggle='tooltip' data-placement='top' title='"+role+"' class='label label-warning'>"+this.ip+"</span>";
                        }else{
                            role = "<span data-toggle='tooltip' data-placement='top' title='"+role+"' class='label label-success'>"+this.ip+"</span>";
                        }
                        html+="<tr>"+
                            "<td><input type='checkbox' name='serverId' value='"+this.ip+"'></td>"+
                            "<td >"+role+"</td>"+
                            "<td class='text-left' id='serverTds"+index+"'>"+showSingleList(processObjList,this.ip)+"</td>"+
                            "<td class='text-left' >"+this.version+"</td>"+
                            "<td class='col-xs-10'><div class='btn-group col-xs-12'>"+
                            "<button type='button' index='"+index+"' optationSingle='start' class='btn btn-info'>启动</button>"+
                            "<button type='button' class='btn btn-info dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>"+
                            "<span class='caret'></span>"+
                            "</button>"+
                            " <ul class='dropdown-menu'>"+
                            " <li><a href='#' index='"+index+"' optationSingle='stop'>停止</a></li>"+
                            " <li><a href='#' index='"+index+"' optationSingle='restart'>发布升级</a></li>"+
                            "</ul>"+
                            "</div></td>"+
                            "</tr>";
                    }

                });
                $("#nodeMessage").html(html);
                //单独启某一个节点方法
                $("[optationSingle]").on("click",singleRestart);
                $("[singleServer]").on("click",singleServer);

            }});
    }


    restAjax("index/projects",window.RequestMethod.GET,{
        success:function(res){
            var html = "";
            var defaultPro = "";
            $(res.data).each(function(index){
                var className = "";
                if(index==0){
                    className = "active";
                    defaultPro = this.value;
                }
                html += '<li projectName="'+this.value+'" class="'+className+'"><a href="#">'+this.name+'</a></li>';
            });
            $("#prjectTabs").html(html);
            $("[projectName]").on("click",function(obj){
                $("[projectName]").removeClass("active");
                $(obj.currentTarget).addClass("active");
                projectName = $(obj.currentTarget).attr("projectName");
                init(projectName);
            });

            init(defaultPro);
        }
    });







    function showSingleList(hasProjectName,ip){
        var html =  '<div class="checkbox">';
        $(hasProjectName).each(function(index){
                var flag = this.run;
                var staticButon = "";
                var className = "";
                if(this.moduleType.name=='WEB'){
                    className = "btn-info";
                    staticButon = '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="static">更新静态文件</a></li>'
                    staticButon += '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="selectStatic">更新静态文件(新)</a></li>'
                }
                if(!flag){
                    html+='<input type="checkbox" value="'+this.moduleName+'"> ';
                    html+='<div class="btn-group">'+
                        '<button class="btn btn-default btn-xs dropdown-toggle '+className+'" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
                        '<s>'+this.moduleName+'</s><span class="caret"></span>'+
                        '</button>'+
                        '<ul class="dropdown-menu">'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="start">重启</a></li>'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="stop">停止</a></li>'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="restart">发布升级</a></li>'+staticButon+
                        ' </ul>'+
                        '</div><br/>';
                }else{
                    html+='<input type="checkbox" checked value="'+this.moduleName+'"> ';
                    html+='<div class="btn-group">'+
                        '<button class="btn btn-default btn-xs dropdown-toggle '+className+'" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
                        this.moduleName+'<span class="caret"></span>'+
                        '</button>'+
                        '<ul class="dropdown-menu">'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="start">重启</a></li>'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="stop">停止</a></li>'+
                        '<li><a href="#" ip="'+ip+'" singleServer="'+this.moduleName+'" optation="restart">发布升级</a></li>'+staticButon+
                        ' </ul>'+
                        '</div><br/>';
                }

            }
        );
        return html;
    }




    //单独发布升级一个节点方法
    function singleRestart(obj){
        var index = $(obj.currentTarget).attr("index");
        var optation = $(obj.currentTarget).attr("optationSingle");
        var checkboxe = $("#serverTds"+index).find(":checkbox").filter(':not([name="serverId"])').filter(':not([disabled])').filter(':checked');
        //var checkboxe = $(obj.currentTarget.parentElement.parentElement).find(":checkbox").filter(':not([name="serverId"])').filter(':not([disabled])').filter(':checked');
        if(checkboxe.length<=0){
            window.Dialog.alert("请选择操作项目");
            return;
        }

        var serverNames = [];
        $(checkboxe).each(function(){
            serverNames.push(this.value)
        });
        var nodeIP = $("#serverTds"+index).parent().find("[name='serverId']").val();
        //var nodeIP = $(obj.currentTarget.parentElement.parentElement).find("[name='serverId']").val();
        var serverInfos = [];
        var serverInfo = {};
        serverInfo.ip = nodeIP;
        serverInfo.processObj = serverNames;
        serverInfos.push(serverInfo);
        restartAjax(serverInfos,projectName,optation);

    }

    //单独发布升级一个节点方法
    function singleServer(obj){
        var singleServer = $(obj.currentTarget).attr("singleServer");
        var optation = $(obj.currentTarget).attr("optation");
        var ip = $(obj.currentTarget).attr("ip");
        var serverNames = [singleServer];
        var serverInfos = [];
        var serverInfo = {};
        serverInfo.ip = ip;
        serverInfo.processObj = serverNames;
        serverInfos.push(serverInfo);
        if("selectStatic" == optation){
            var zNodes =[
            ];
            zNodes.push({id:"/",ip:ip,pId:0,appName:singleServer,name:singleServer,isParent:true})
            t = $.fn.zTree.init($("#tree"), setting, zNodes);
            $('#staticRestartDiv').modal({backdrop:false});
        }else{
            restartAjax(serverInfos,projectName,optation);
        }
    }


    function restartAjax(serverInfos,name,optation){
        window.Dialog.prompt({titel:"添加备注信息",func:function(remark){
            restAjax("index/reStart",window.RequestMethod.POST,{
                    data:{serverInfos:serverInfos,projectName:name,optation:optation,remark:remark},
                    success:function(data){
                        if(!data.suc){
                            window.Dialog.alert(data.data.errorContent);
                        }else{
                            init(projectName);
                        }
                    }
                }
            );
        }});

    }



    //全选
    $("#checkAll").on("click",function(obj){
        var checked = true;
        if(!obj.target.checked){
            checked = false;
        }
        $("[name=serverId]").each(function(){
            this.checked = checked;
        });
    });

    $("#releaseStatic").on("click",function(){
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getCheckedNodes(true);
        if(nodes.length==0){
            window.Dialog.alert("请选择文件")
        }
        var releaseNodes = [];
        $(nodes).each(function(){
            if(!this.isParent){
                releaseNodes.push(this)
            }
        });
        if(releaseNodes.length==0){
            window.Dialog.alert("请选择文件")
        }
        var serverInfos = [];
        var serverInfo = {};
        serverInfo.ip = releaseNodes[0].ip;
        serverInfo.processObj = [releaseNodes[0].appName];
        serverInfo.staticFiles = releaseNodes;
        serverInfos.push(serverInfo);
        console.log(releaseNodes);
        restartAjax(serverInfos,projectName,"static");
        $('#staticRestartDiv').modal('hide')
    });

    //发布升级所有节点方法
    $("[optationAll]").on("click",function(obj){
        //$("#reStartAll").on("click",function(obj){
        var serverInfos = [];
        var flag = true;
        $("[name=serverId]").each(function(){
            var serverInfo = {};
            if(this.checked){
                var checkboxe = $(this.parentNode.parentNode).find(":checkbox").filter(':not([disabled])').filter(':not([name="serverId"])').filter(':checked');
                if(checkboxe.length<=0){
                    window.Dialog.alert("请选择节点 "+this.value+" ，操作项目");
                    flag = false;
                    return;
                }
                var serverName = [];
                $(checkboxe).each(function(){
                    serverName.push(this.value)
                });
                console.log(serverName);
                serverInfo.ip = this.value;
                serverInfo.processObj = serverName;
                serverInfos.push(serverInfo)
            }
        });
        if(!flag || serverInfos.length == 0){
            window.Dialog.alert("请选择节点!");
            return;
        }
        restartAjax(serverInfos,projectName,$(obj.currentTarget).attr("optationAll"));

    });


    var setting = {
        treeId:"staticTree",
        check: {
            enable: true
        },
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
        },
        async: {
            enable: true,
            url: getAsyncUrl,
            autoParam: ["id", "name"]
        },
        data: {
            simpleData: {
                enable:true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        }
    };

    var zNodes =[
        {id:"/122", pId:0, name:"[core] 基本功能 演示", open:true},
        {id:"/Wms", pId:0, name:"[core] 基本功能 演示", open:true}
    ];

    function getAsyncUrl(treeId, treeNode) {
        return "index/treeNode?parentId="+treeNode.id+"&ip="+treeNode.ip+"&projectName="+projectName+"&appName="+treeNode.appName;
    };

})(jQuery);